using System.Collections.Generic;
using System.Linq;
using Sprache;

namespace ExternalDSL.EmailFormLanguage
{
	public static class EmailFormParser
	{
		public static readonly Parser<string> Identifier = Parse.LetterOrDigit.AtLeastOnce().Text().Token();

		public static readonly Parser<string> Label =
			(from start in Parse.Char('"')
			 from content in Parse.CharExcept('"').Many().Text()
			 from end in Parse.Char('"')
			 select content).Token();

		public static readonly Parser<Field> Field =
			from id in Identifier
			from label in Label
			select new Field(id, label);

		public static readonly Parser<IEnumerable<Field>> UserFields =
			from area in Parse.String("Fields")
			from start in Parse.Char('{').Token()
			from fields in Field.Many()
			from end in Parse.Char('}').Token()
			select fields;

		public static readonly Parser<Form> Form =
			from area in Parse.String("Form")
			from start in Parse.Char('[').Token()
			from fields in Field.Many()
			from userFields in UserFields
			from end in Parse.Char(']').Token()
			select new Form(
				fields.Where(w => w.Name == "From").FirstOrDefault(),
				fields.Where(w => w.Name == "To").FirstOrDefault(),
				fields.Where(w => w.Name == "Subject").FirstOrDefault(),
				userFields
				);
	}
}